import React, { useRef, useState } from 'react'
import './app.css'
export default function App() {
  const fileRef = useRef(null)
  const [imagePreview, setImagePreview] = useState('https://res.bearbobo.com/resource/upload/W44yyxvl/upload-ih56twxirei.png')
  const [imageUrl, setImageUrl] = useState('ddd')
  const [status,setStatus] = useState('')//工作流当前的状态
  const updateImageData = () => {
    const file = fileRef.current.files[0]
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => {
      setImagePreview(reader.result)
    }
  }
  const [uniform_number,setUniformNumber] = useState(10)
  const [uniform_color,setUniformColor] = useState('红')
  const [position,setPosition] = useState(0)
  const [shooting_hand,setShootingHand] = useState('左手')
  const [style,setStyle] = useState('传统')

  const patToken=import.meta.env.VITE_PAT_TOKEN
  const uploadUrl= 'https://api.coze.cn/v1/files/upload'//上传和鉴权地址
  const workflowUrl = 'https://api.coze.cn/v1/workflow/run'//工作流地址
  const workflow_id = '7536407996395454499'//工作流id
  async function uploadFile(){
    const formData=new FormData()//用于上传表单文件，只能存储字符串和 Blob/File 对象
    const inputFile=fileRef.current.files[0]
    if(!inputFile){
      return
    }
    formData.append('file',inputFile)//添加键值对
    const res=await fetch(uploadUrl,{
      method:'POST',
      headers:{
        'Authorization':`Bearer ${patToken}`,
      },
      body:formData
    })
    const ret=await res.json()
    if(ret.code!==0){
      console.log(ret);
      return
    }
    return ret.data.id
  }
  const generate = async() => {
    // 上传图片
    setStatus('上传中...')
    const file_id = await uploadFile()
    setStatus('上传完成，正在生成...')

    // 调用工作流
    const res = await fetch(workflowUrl, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${patToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        workflow_id,
        parameters: {
          picture: {file_id},
          style,
          uniform_number:Number(uniform_number),
          uniform_color,
          position:Number(position),
          shooting_hand:Number(shooting_hand),
        }
      })
    })
    const ret = await res.json()
    console.log(ret);
    const data=JSON.parse(ret.data).answer
    setStatus('生成完成')
    setImageUrl(data)
  }


  return (
    <div className='container'>
      <div className="input">
        <div className="file-input">
          <input type="file" id="image" name='image' accept='image/*' required onChange={updateImageData} ref={fileRef} />
        </div>
        <img className='preview' src={imagePreview} alt="preview" />
        <div className="settings">
          <div className="selection">
            <label>队服编号</label>
            <input type="number" onChange={(e) => setUniformNumber(e.target.value)} />
          </div>
          <div className="selection">
            <label htmlFor="">队服颜色</label>
            <select onChange={(e) => setUniformColor(e.target.value)}>
              <option value="红">红</option>
              <option value="蓝">蓝</option>
              <option value="黄">黄</option>
              <option value="绿">绿</option>
              <option value="紫">紫</option>
              <option value="橙">橙</option>
              <option value="棕">棕</option>
              <option value="粉">粉</option>
            </select>
          </div>
        </div>
        <div className="settings">
          <div className="selection">
            <label>位置:</label>
            <select onChange={(e) => setPosition(e.target.value)}>
              <option value="0">守门员</option>
              <option value="1">前锋</option>
              <option value="2">后卫</option>
            </select>
          </div>
          <div className="selection">
            <label>持杆:</label>
            <select onChange={(e) => setShootingHand(e.target.value)}>
              <option value="0">左手</option>
              <option value="1">右手</option>
            </select>
          </div>
          <div className="selection">
            <label>风格</label>
            <select onChange={(e) => setStyle(e.target.value)}>
              <option value="传统">传统</option>
              <option value="现代">现代</option>
              <option value="运动">运动</option>
              <option value="古典">古典</option>
              <option value="极简">极简</option>
              <option value="运动">运动</option>
              <option value="卡通">卡通</option>
              <option value="素描">素描</option>
            </select>
          </div>
        </div>
        <div className="generate">
          <button onClick={generate}>生成</button>
        </div>
      </div>
      <div className="output">
        <div className="generated">
          <div>{status}</div>
          <img src={imageUrl} alt="" />
        </div>
      </div>
    </div>
  )
}
